﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;

namespace AuthenticationToken
{
    internal static class Cryptography
    {
        internal static string Encrypt(string plainText, string key)
        {
            string encryptedData = EncryptText(plainText, key);
            byte[] encryptedBytes = System.Text.UTF8Encoding.UTF8.GetBytes(encryptedData);
            return HttpServerUtility.UrlTokenEncode(encryptedBytes);
        }
        internal static string Decrypt(string encryptedText, string key)
        {
            byte[] decryptedBytes = HttpServerUtility.UrlTokenDecode(encryptedText);
            encryptedText = System.Text.UTF8Encoding.UTF8.GetString(decryptedBytes);
            return DecryptText(encryptedText, key);
        }
        private static string EncryptText(string plainText, string key)
        {
            byte[] buffer = Encryption(plainText, key);
            string encryptedText = Convert.ToBase64String(buffer);
            return encryptedText;
        }
        private static string DecryptText(string encryptedText, string key)
        {
            byte[] b = Convert.FromBase64String(encryptedText);
            TripleDES des = CreateDES(key);
            ICryptoTransform ct = des.CreateDecryptor();
            byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
            return Encoding.Unicode.GetString(output);
        }
        private static byte[] Encryption(string plainText, string key)
        {
            TripleDES des = CreateDES(key);

            ICryptoTransform ct = des.CreateEncryptor();

            byte[] input = Encoding.Unicode.GetBytes(plainText);

            return ct.TransformFinalBlock(input, 0, input.Length);
        }
        private static TripleDES CreateDES(string key)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            TripleDES des = new TripleDESCryptoServiceProvider();
            des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
            des.IV = new byte[des.BlockSize / 8];
            return des;
        }
    }
}
